import { BaseService } from '@/core/base.service';
import { PointsListDto } from '@/dtos';
import { Injectable } from '@nestjs/common';
import { Points } from '@prisma/client';

@Injectable()
export class PointsService extends BaseService {
  async getList(ownerId: number, { params, sort }: PointsListDto) {
    const { current = 1, pageSize = 20, keyword, ...where } = params;

    let sql = `
      SELECT #{fields} FROM Points AS t
      WHERE t.isDeleted = false
        AND t.ownerId = ${ownerId}
        ${!!where.type && Number(where.type) > 0 ? `AND t.type = ${where.type}` : ''}
    `;

    const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: number }]>(
      sql.replace('#{fields}', 'COUNT(t.id) AS count'),
    );

    const list = await this.prisma.$queryRawUnsafe<Points[]>(
      `${sql.replace('#{fields}', 't.id, t.type, t.total, t.log, t.createdAt')}
      ORDER BY ${
        !!sort && Object.keys(sort).length > 0
          ? Object.entries(sort)
              .map(([k, v]) => `t.${k} ${v === 'descend' ? 'DESC' : 'ASC'}`)
              .join(',')
          : 't.createdAt DESC'
      }
      LIMIT ${pageSize} 
      OFFSET ${(current - 1) * pageSize}
      `,
    );

    const total = count ? Number(count) : 0;
    const totalPage = Math.ceil(total / pageSize);
    const hasMore = current < totalPage;

    return {
      total,
      totalPage,
      hasMore,
      current,
      pageSize,
      list: list.map((o) => ({
        ...o,
        total: Number(o.total),
      })),
    };
  }
}
